package com.cloud.pdd.controller.ajax;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.common.security.AES;
import com.cloud.common.util.CookieUtils;
import com.cloud.common.util.R;
import com.cloud.pdd.model.domain.UserInfo;
import com.cloud.pdd.model.entity.PddFinances;
import com.cloud.pdd.model.entity.PddUsers;
import com.cloud.pdd.model.enums.CookieConst;
import com.cloud.pdd.service.PddFinancesService;
import com.cloud.pdd.service.PddUsersService;
import com.cloud.pdd.model.request.LoginRequest;
import com.cloud.pdd.model.request.RegRequest;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;

@RestController
@RequestMapping("ajax/user")
@AllArgsConstructor
public class AjaxUserController {

    private final PddUsersService pddUsersService;
    private final PddFinancesService pddFinancesService;

    //注册
    @ResponseBody
    @PostMapping("reg")
    public R reg(HttpServletRequest request, HttpServletResponse response,
                 RegRequest req) {
        if (StrUtil.length(Convert.toStr(req.getMobile())) != 11) {
            return new R().setMsg("请输入正确手机号");
        }
        if (StrUtil.length(req.getPassword()) < 6 || StrUtil.length(req.getPassword()) > 30
                || StrUtil.compareIgnoreCase(req.getPassword(), req.getPasswordConfirm(), false) != 0
        ) {
            return new R().setMsg("请输入正确密码");
        }

//        String code = req.getCode();
//        String codeKey = CookieConst.loginPddUserCode;
//        String cookie = CookieUtils.getCookie(request, codeKey);
//        String decode = AES.aesDecrypt(cookie);
//        if (code.length() != 4 || !code.equals(decode)) {
//            return new R().setMsg("请输入正确验证码");
//        }

        //查询用户名称是否存在
        //查询手机号是否存在
        QueryWrapper queryWrapperMobileCount = new QueryWrapper();
        queryWrapperMobileCount.eq("mobile", req.getMobile());
        int count = pddUsersService.count(queryWrapperMobileCount);
        if (count > 0) {
            return new R().setMsg("当前手机号已存在，请换个手机号");
        }
        PddUsers pddUsers = new PddUsers();
        BeanUtil.copyProperties(req, pddUsers);
        pddUsers.setUsername(req.getUsername());
        pddUsers.setPassword(AES.aesEncrypt(req.getPassword()));
        boolean result = pddUsersService.save(pddUsers);
        //创建账户
        PddFinances pddFinances = new PddFinances();
        pddFinances.setUserId(pddUsers.getId());
        pddFinancesService.save(pddFinances);
        //创建Pid账户
        String beiAnUrl = pddUsersService.getBeiAnUrl(pddUsers.getId());
        if (!result) {
            return new R().setCode(0).setMsg("请输入正确的账号密码");
        }
        loginDo(request, response, pddUsers);
        R r = new R();
        r.setCode(1);
        r.setData(beiAnUrl);
        return r;
    }

    //退出
    @ResponseBody
    @GetMapping("logout")
    public R logout(HttpServletRequest request, HttpServletResponse response) {
        String loginKey = CookieConst.loginPddCookie;
        CookieUtils.deleteCookie(request, response, loginKey);
        return new R();
    }

    //登录
    @ResponseBody
    @PostMapping("login")
    public R login(HttpServletRequest request, HttpServletResponse response,
                   LoginRequest req) {
        String code = req.getCode();
        String codeKey = CookieConst.loginPddUserCode;
        String cookie = CookieUtils.getCookie(request, codeKey);
        String decode = AES.aesDecrypt(cookie);
        if (code.length() != 4 || !code.equals(decode)) {
            return new R().setCode(0).setMsg("请输入正确验证码");
        }
        String pwd = AES.aesEncrypt(req.getPassword());
        QueryWrapper queryWrapperLogin = new QueryWrapper();
        queryWrapperLogin.eq("mobile", req.getMobile());
        queryWrapperLogin.eq("password", pwd);
        PddUsers bUsersResult = pddUsersService.getOne(queryWrapperLogin);
        if (null == bUsersResult) {
            return new R().setCode(0).setMsg("请输入正确的账号密码");
        }
        loginDo(request, response, bUsersResult);
        return new R();
    }

    //登录
    private void loginDo(HttpServletRequest request, HttpServletResponse response, PddUsers bUsersResult) {
        //记录登录cookie
        UserInfo userInfo = new UserInfo();
        userInfo.setId(bUsersResult.getId());
        String nickName = bUsersResult.getNickName();
        if (StrUtil.isEmpty(nickName)) {
            nickName = bUsersResult.getUsername();
        }
        userInfo.setNickname(nickName);
        userInfo.setPhoto(bUsersResult.getPhoto());
        userInfo.setLoginTime(DateUtil.current());
        String userinfoData = JSONUtil.toJsonStr(userInfo);
        String userinfoEncode = AES.aesEncrypt(userinfoData);
        String loginKey = CookieConst.loginPddCookie;
        CookieUtils.setCookie(request, response, loginKey, userinfoEncode);
    }

    //获取验证码
    @GetMapping("getCode")
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String key = CookieConst.loginPddUserCode;
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(116, 36, 4, 5);
        //得到code
        String code = captcha.getCode();
        System.out.println(code);
        //放到session
        String s = AES.aesEncrypt(code);
        CookieUtils.setCookie(request, response, key, s);
        //输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //读写输出流
        captcha.write(outputStream);
        //关闭输出流
        outputStream.close();
    }
}
